package apptoko.com.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu.OnItemSelectedListener;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;
import apptoko.com.ConfirmBuyActivity;
import apptoko.com.ItemBrokerActivity;
import apptoko.com.LoginActivity;
import apptoko.com.VideoActivity;
import apptoko.com.background.BackgroundTasks;
import apptoko.com.background.PackageEventReceiver;
import apptoko.com.db.DatabaseHelper;
import apptoko.com.download.DownloadManager;
import apptoko.com.download.DownloadService;
import apptoko.com.download.DownloadManager.Request;
import apptoko.com.event.Event.BuyFailEvent;
import apptoko.com.event.Event.BuySuccessEvent;
import apptoko.com.event.Event.GetDownloadLinkFailEvent;
import apptoko.com.event.Event.GetDownloadLinkSuccess;
import apptoko.com.event.Event.GetVersionListSuccessEvent;
import apptoko.com.event.Event.GetWishListSuccessEvent;
import apptoko.com.event.Event.UserInfoSuccessEvent;
import apptoko.com.model.DownloadLaterItem;
import apptoko.com.model.DownloadLink;
import apptoko.com.network.ProgressDialogManager;
import apptoko.com.util.Constants;
import apptoko.com.util.StorageUtils;
import apptoko.com.util.Utils;
import apptoko.com.view.AlertDialogManager;

import com.androidquery.AQuery;
import com.appota.asdk.commons.AccessTokenUtil;
import com.appota.asdk.topup.TopupAPI;
import apptoko.com.R;
import com.devspark.appmsg.AppMsg;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

public class WishlistFragment extends BaseFragment implements OnItemClickListener {
	
	private AQuery aq;
	private String type;
	private List<DownloadLaterItem> listItem;
	private DatabaseHelper db;
	private ProgressDialog pDialog;
	private int greenTym = -1;
	private int purpleTym = -1;
	private BackgroundTasks bgTask;
	private DownloadManager downloadManager;
	private DownloadLaterItem contentItem;
	private boolean isWatchMovie = false;
	private String versionName = "";
	private DownloadLaterAdapter adapter;
	private PackageEventReceiver receiver;
	private String countryCode;
	private boolean enaG=false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mParent = inflater.inflate(R.layout.tab_wishlist, null);
		aq = new AQuery(mParent);
		aq.id(R.id.wish_list).adapter(adapter).itemClicked(this);
		return mParent;
	}

	@Override
	protected void initVariables() {
		// TODO Auto-generated method stub
		countryCode = Utils.getStaticCountryCode(mContext);
		SharedPreferences shared= getActivity().getSharedPreferences("system_pre", Activity.MODE_PRIVATE);
		enaG=shared.getBoolean(Constants.ENABLE_GUEST, false);
		type = getArguments().getString(Constants.STORE_KEY);
		db = new DatabaseHelper(mContext);
		bgTask = new BackgroundTasks(mContext);
		listItem = new ArrayList<DownloadLaterItem>();
		adapter = new DownloadLaterAdapter(mContext, R.layout.download_later_item, listItem);
		downloadManager = new DownloadManager(mContext.getContentResolver(), mContext.getPackageName());
	    downloadManager.setAccessAllDownloads(false);
		startDownloadService();
		
		receiver = new PackageEventReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_PACKAGE_ADDED);
		filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		filter.addDataScheme("package");
		mContext.registerReceiver(receiver, filter);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mContext.unregisterReceiver(receiver);
	}

	@Override
	protected void initActions() {
		// TODO Auto-generated method stub
		getUserInfo();
		getWishList();
	}
	
	private void getUserInfo(){
		String accessToken = Utils.getStaticAccessToken(getActivity());
		if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
			bgTask.getUserInfo(accessToken);
		}
	}
	
	public void onEventMainThread(UserInfoSuccessEvent event){
		greenTym = event.getUser().getGreenTym();
		purpleTym = event.getUser().getPurpleTym();
		getActivity().getSharedPreferences(Constants.SHARED_NAME, Activity.MODE_PRIVATE).edit().putString(Constants.USERNAME_LOGGEDIN, event.getUser().getUserName()).commit();
	}
	
	private void startDownloadService() {
		Intent intent = new Intent();
		intent.setClass(getActivity(), DownloadService.class);
		getActivity().startService(intent);
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		EventBus.getDefault().unregister(this);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		EventBus.getDefault().register(this);
	}
	
	private void getWishList(){
		AsyncExecutor.create().execute(new RunnableEx() {
			@Override
			public void run() throws Exception {
				// TODO Auto-generated method stub
				List<DownloadLaterItem> list = db.getDownloadLaterItem(type);
				EventBus.getDefault().post(new GetWishListSuccessEvent(list));
			}
		});
	}
	
	public void onEventMainThread(GetWishListSuccessEvent e){
		if(e.getList().size() > 0){
			aq.id(R.id.progress_wishlist).gone();
			aq.id(R.id.empty_view).gone();
			aq.id(R.id.wish_list).visible();
			for(DownloadLaterItem item : e.getList()){
				listItem.add(item);
			}
			adapter.notifyDataSetChanged();
		} else {
			aq.id(R.id.progress_wishlist).gone();
			aq.id(R.id.empty_view).visible();
			aq.id(R.id.wish_list).gone();
		}
	}

	@SuppressLint("NewApi")
	private class DownloadLaterAdapter extends ArrayAdapter<DownloadLaterItem> {
		
		private AQuery aq;
		private Typeface robotoCondensed;
		private Typeface robotoBoldCondensed;
		private Typeface robotoMedium;

		public DownloadLaterAdapter(Context context, int resource, List<DownloadLaterItem> objects) {
			super(context, resource, objects);
			// TODO Auto-generated constructor stub
			robotoBoldCondensed = Typeface.createFromAsset(context.getAssets(),context.getResources().getString(R.string.roboto_bold_condensed));
			robotoCondensed = Typeface.createFromAsset(context.getAssets(), context.getResources().getString(R.string.roboto_condensed));
			robotoMedium = Typeface.createFromAsset(context.getAssets(), context.getResources().getString(R.string.roboto_medium));
		}
		
		private int getColor(String store) {
			int colorId = R.color.app_indicator;
			if (store.equalsIgnoreCase("android")) {
				colorId = R.color.app_indicator;
			} else if (store.equalsIgnoreCase("ebook")) {
				colorId = R.color.ebook_indicator;
			} else if (store.equalsIgnoreCase("comic")) {
				colorId = R.color.comic_indicator;
			} else if (store.equalsIgnoreCase("film")) {
				colorId = R.color.film_indicator;
			}
			return getResources().getColor(colorId);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if(convertView == null){
				convertView = getActivity().getLayoutInflater().inflate(R.layout.download_later_item, null);
				holder = new ViewHolder();
				holder.icon = (ImageView) convertView.findViewById(R.id.icon);
				holder.author = (TextView) convertView.findViewById(R.id.author);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.price = (TextView) convertView.findViewById(R.id.price);
				holder.tym = (ImageView) convertView.findViewById(R.id.price_unit);
				holder.btnMenu = (ImageButton) convertView.findViewById(R.id.btn_quick_menu);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final DownloadLaterItem item = getItem(position);
			if(item != null){
				aq = new AQuery(convertView);
				float ratio = AQuery.RATIO_PRESERVE;
				if(type.equalsIgnoreCase("comic") || type.equalsIgnoreCase("ebook")){
					ratio = 1.0f / 1.0f;
				}
				aq.id(holder.icon).image(item.getImageUrl(), false, true, 0, 0, null, AQuery.FADE_IN_NETWORK, ratio);
				aq.id(holder.name).text(item.getAppName()).typeface(robotoBoldCondensed);
				aq.id(holder.author).text(item.getAuthor()).typeface(robotoCondensed);
				if(type.equalsIgnoreCase("android")){
					if(item.isInstalled()){
						aq.id(holder.price).text(getResources().getString(R.string.installed).toUpperCase(Locale.US)).typeface(robotoMedium).textColor(getColor(type));
						aq.id(holder.tym).invisible();
						aq.id(holder.btnMenu).clicked(new OnClickListener() {
							@Override
							public void onClick(View v) {
								if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
									PopupMenu menu = new PopupMenu(mContext, v);
									menu.getMenuInflater().inflate(R.menu.installed_wishlist_menu, menu.getMenu());
									menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
										@Override
										public boolean onMenuItemClick(MenuItem menuItem) {
											switch (menuItem.getItemId()) {
											case R.id.menu_launch:
												Utils.launch(mContext, item.getPackageName());
												break;
											case R.id.menu_uninstall:
												Utils.uninstallAPK(mContext, item.getPackageName());
												break;
											case R.id.menu_delete:
												db.deleteDownloadLater(item.getSlug());
												remove(item);
												notifyDataSetChanged();
												break;
											}
											return true;
										}
									});
									menu.show();
								} else {
									main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(mContext);
									popupMenuCompat.add(1, R.string.menu_launch);
									popupMenuCompat.add(2, R.string.menu_uninstall);
									popupMenuCompat.add(3, R.string.menu_delete_wishlist);
									popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
										@Override
										public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
											switch (menuItem.getItemId()) {
											case 1:
												Utils.launch(mContext, item.getPackageName());
												break;
											case 2:
												Utils.uninstallAPK(mContext, item.getPackageName());
												break;
											case 3:
												db.deleteDownloadLater(item.getSlug());
												remove(item);
												notifyDataSetChanged();
												break;
											}
										}
									});
									popupMenuCompat.show(v);
								}
							}
						});
					} else {
						if (item.getPrice1() == 0 && item.getPrice2() == 0) {
							aq.id(holder.price).text(getResources().getString(R.string.free).toUpperCase(Locale.US)).typeface(robotoMedium).textColor(getColor(type));
							aq.id(holder.tym).invisible();
						} else if (item.getPrice1() == 0 && item.getPrice2() != 0) {
							aq.id(holder.price).text(String.valueOf(item.getPrice2())).typeface(robotoMedium).textColor(getResources().getColor(R.color.gift_indicator));
							aq.id(holder.tym).image(R.drawable.tym_purple).visible();
						} else if (item.getPrice1() != 0 && item.getPrice2() == 0) {
							aq.id(holder.price).text(String.valueOf(item.getPrice1())).typeface(robotoMedium).textColor(getResources().getColor(R.color.app_indicator));
							aq.id(holder.tym).image(R.drawable.tym_green).visible();
						}
						aq.id(holder.btnMenu).clicked(new OnClickListener() {
							@Override
							public void onClick(View v) {
								if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
									PopupMenu menu = new PopupMenu(mContext, v);
									menu.getMenuInflater().inflate(R.menu.not_installed_wish_menu, menu.getMenu());
									menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
										@Override
										public boolean onMenuItemClick(MenuItem menuItem) {
											switch (menuItem.getItemId()) {
											case R.id.menu_install:
												contentItem = item;
												if(enaG){
													if(true){//checkLogin()
														pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
														if(item.getPrice1() != 0){
															validAndBuy(item.getPrice1(), "green", item, 0);
														} else if(item.getPrice2() != 0){
															validAndBuy(item.getPrice2(), "purple", item, 0);
														} else {
															validAndBuy(0, "free", item, 0);
														}
													} else {
														AlertDialogManager am = new AlertDialogManager(mContext);
														am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
															@Override
															public void onClick(DialogInterface dialog, int which) {
																// TODO Auto-generated method stub
																switch (which) {
																case DialogInterface.BUTTON_POSITIVE:
																	Intent intent = new Intent(getActivity(), LoginActivity.class);
																	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
																	startActivity(intent);
																	break;
																case DialogInterface.BUTTON_NEGATIVE:
																	dialog.dismiss();
																	break;
																}
															}
														});
													}
												}else{
													if(!countryCode.equalsIgnoreCase("vn")&&!countryCode.equalsIgnoreCase("id")&&!countryCode.equalsIgnoreCase("my")){
//														Intent gp = new Intent(Intent.ACTION_VIEW);
//														gp.setData(Uri.parse(item.getRootLink()));
//														startActivity(gp);
													} else {
														isWatchMovie = false;
														if(true){//checkLogin()
															pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
															if(item.getPrice1() != 0){
																validAndBuy(item.getPrice1(), "green", item, 0);
															} else if(item.getPrice2() != 0){
																validAndBuy(item.getPrice2(), "purple", item, 0);
															} else {
																validAndBuy(0, "free", item, 0);
															}
														} else {
															AlertDialogManager am = new AlertDialogManager(mContext);
															am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
																@Override
																public void onClick(DialogInterface dialog, int which) {
																	// TODO Auto-generated method stub
																	switch (which) {
																	case DialogInterface.BUTTON_POSITIVE:
																		Intent intent = new Intent(getActivity(), LoginActivity.class);
																		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
																		startActivity(intent);
																		break;
																	case DialogInterface.BUTTON_NEGATIVE:
																		dialog.dismiss();
																		break;
																	}
																}
															});
														}
													}
												}
												
												break;
											case R.id.menu_remove:
												db.deleteDownloadLater(item.getSlug());
												remove(item);
												notifyDataSetChanged();
												break;
											}
											return true;
										}
									});
									menu.show();
								} else {
									main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(mContext);
									popupMenuCompat.add(1, R.string.install);
									popupMenuCompat.add(2, R.string.menu_delete_wishlist);
									popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
										@Override
										public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
											switch (menuItem.getItemId()) {
											case 1:
												contentItem = item;
												if(!countryCode.equalsIgnoreCase("vn")){
//													Intent gp = new Intent(Intent.ACTION_VIEW);
//													gp.setData(Uri.parse(item.getRootLink()));
//													startActivity(gp);
												} else {
													isWatchMovie = false;
													if(checkLogin()){
														pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
														if(item.getPrice1() != 0){
															validAndBuy(item.getPrice1(), "green", item, 0);
														} else if(item.getPrice2() != 0){
															validAndBuy(item.getPrice2(), "purple", item, 0);
														} else {
															validAndBuy(0, "free", item, 0);
														}
													} else {
														AlertDialogManager am = new AlertDialogManager(mContext);
														am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
															@Override
															public void onClick(DialogInterface dialog, int which) {
																// TODO Auto-generated method stub
																switch (which) {
																case DialogInterface.BUTTON_POSITIVE:
																	Intent intent = new Intent(getActivity(), LoginActivity.class);
																	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
																	startActivity(intent);
																	break;
																case DialogInterface.BUTTON_NEGATIVE:
																	dialog.dismiss();
																	break;
																}
															}
														});
													}
												}
												break;
											case 2:
												db.deleteDownloadLater(item.getSlug());
												remove(item);
												notifyDataSetChanged();
												break;
											}
										}
									});
									popupMenuCompat.show(v);
								}
							}
						});
					}
				} else if(type.equalsIgnoreCase("ebook") || type.equalsIgnoreCase("comic")){
					if (item.getPrice1() == 0 && item.getPrice2() == 0) {
						aq.id(holder.price).text(getResources().getString(R.string.free).toUpperCase(Locale.US)).typeface(robotoMedium).textColor(getColor(type));
						aq.id(holder.tym).invisible();
					} else if (item.getPrice1() == 0 && item.getPrice2() != 0) {
						aq.id(holder.price).text(String.valueOf(item.getPrice2())).typeface(robotoMedium).textColor(getResources().getColor(R.color.gift_indicator));
						aq.id(holder.tym).image(R.drawable.tym_purple).visible();
					} else if (item.getPrice1() != 0 && item.getPrice2() == 0) {
						aq.id(holder.price).text(String.valueOf(item.getPrice1())).typeface(robotoMedium).textColor(getResources().getColor(R.color.app_indicator));
						aq.id(holder.tym).image(R.drawable.tym_green).visible();
					}
					aq.id(holder.btnMenu).clicked(new OnClickListener() {
						@Override
						public void onClick(View v) {
							if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
								PopupMenu menu = new PopupMenu(mContext, v);
								menu.getMenuInflater().inflate(R.menu.book_comic_wish_menu, menu.getMenu());
								menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
									@Override
									public boolean onMenuItemClick(MenuItem menuItem) {
										switch (menuItem.getItemId()) {
										case R.id.menu_download:
											contentItem = item;
											isWatchMovie = false;
											if(checkLogin()){
												pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
												if(item.getPrice1() != 0){
													validAndBuy(item.getPrice1(), "green", item, 0);
												} else if(item.getPrice2() != 0){
													validAndBuy(item.getPrice2(), "purple", item, 0);
												} else {
													validAndBuy(0, "free", item, 0);
												}
											} else {
												AlertDialogManager am = new AlertDialogManager(mContext);
												am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
													@Override
													public void onClick(DialogInterface dialog, int which) {
														// TODO Auto-generated method stub
														switch (which) {
														case DialogInterface.BUTTON_POSITIVE:
															Intent intent = new Intent(getActivity(), LoginActivity.class);
															intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
															startActivity(intent);
															break;
														case DialogInterface.BUTTON_NEGATIVE:
															dialog.dismiss();
															break;
														}
													}
												});
											}
											break;
										case R.id.menu_remove:
											db.deleteDownloadLater(item.getSlug());
											remove(item);
											notifyDataSetChanged();
											break;
										}
										return true;
									}
								});
								menu.show();
							} else {
								main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(mContext);
								popupMenuCompat.add(1, R.string.download);
								popupMenuCompat.add(2, R.string.menu_delete_wishlist);
								popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
									@Override
									public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
										switch (menuItem.getItemId()) {
										case 1:
											contentItem = item;
											isWatchMovie = false;
											if(checkLogin()){
												pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
												if(item.getPrice1() != 0){
													validAndBuy(item.getPrice1(), "green", item, 0);
												} else if(item.getPrice2() != 0){
													validAndBuy(item.getPrice2(), "purple", item, 0);
												} else {
													validAndBuy(0, "free", item, 0);
												}
											} else {
												AlertDialogManager am = new AlertDialogManager(mContext);
												am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
													@Override
													public void onClick(DialogInterface dialog, int which) {
														// TODO Auto-generated method stub
														switch (which) {
														case DialogInterface.BUTTON_POSITIVE:
															Intent intent = new Intent(getActivity(), LoginActivity.class);
															intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
															startActivity(intent);
															break;
														case DialogInterface.BUTTON_NEGATIVE:
															dialog.dismiss();
															break;
														}
													}
												});
											}
											break;
										case 2:
											db.deleteDownloadLater(item.getSlug());
											remove(item);
											notifyDataSetChanged();
											break;
										}
									}
								});
								popupMenuCompat.show(v);
							}
						}
					});
				} else if(type.equalsIgnoreCase("film")){
					if (item.getPrice1() == 0 && item.getPrice2() == 0) {
						aq.id(holder.price).text(getResources().getString(R.string.free).toUpperCase(Locale.US)).typeface(robotoMedium).textColor(getColor(type));
						aq.id(holder.tym).invisible();
					} else if (item.getPrice1() == 0 && item.getPrice2() != 0) {
						aq.id(holder.price).text(String.valueOf(item.getPrice2())).typeface(robotoMedium).textColor(getResources().getColor(R.color.gift_indicator));
						aq.id(holder.tym).image(R.drawable.tym_purple).visible();
					} else if (item.getPrice1() != 0 && item.getPrice2() == 0) {
						aq.id(holder.price).text(String.valueOf(item.getPrice1())).typeface(robotoMedium).textColor(getResources().getColor(R.color.app_indicator));
						aq.id(holder.tym).image(R.drawable.tym_green).visible();
					}
					aq.id(holder.btnMenu).clicked(new OnClickListener() {
						@Override
						public void onClick(View v) {
							contentItem = item;
							isWatchMovie = true;
							if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
								PopupMenu menu = new PopupMenu(mContext, v);
								menu.getMenuInflater().inflate(R.menu.movie_wish_menu, menu.getMenu());
								menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
									@Override
									public boolean onMenuItemClick(MenuItem menuItem) {
										switch (menuItem.getItemId()) {
										case R.id.menu_watch:
											contentItem = item;
											if(checkLogin()){
												pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
												String accessToken = Utils.getStaticAccessToken(getActivity());
												bgTask.getVersionList(accessToken, item.getSlug(), "");
											} else {
												AlertDialogManager am = new AlertDialogManager(mContext);
												am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
													@Override
													public void onClick(DialogInterface dialog, int which) {
														// TODO Auto-generated method stub
														switch (which) {
														case DialogInterface.BUTTON_POSITIVE:
															Intent intent = new Intent(getActivity(), LoginActivity.class);
															intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
															startActivity(intent);
															break;
														case DialogInterface.BUTTON_NEGATIVE:
															dialog.dismiss();
															break;
														}
													}
												});
											}
											break;
										case R.id.menu_remove:
											db.deleteDownloadLater(item.getSlug());
											remove(item);
											notifyDataSetChanged();
											break;
										}
										return true;
									}
								});
								menu.show();
							} else {
								main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenuCompat = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(mContext);
								popupMenuCompat.add(1, R.string.watch);
								popupMenuCompat.add(2, R.string.menu_delete_wishlist);
								popupMenuCompat.setOnItemSelectedListener(new OnItemSelectedListener() {
									@Override
									public void onItemSelected(main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
										switch (menuItem.getItemId()) {
										case 1:
											if(checkLogin()){
												pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
												if(item.getPrice1() != 0){
													validAndBuy(item.getPrice1(), "green", item, 0);
												} else if(item.getPrice2() != 0){
													validAndBuy(item.getPrice2(), "purple", item, 0);
												} else {
													validAndBuy(0, "free", item, 0);
												}
											} else {
												AlertDialogManager am = new AlertDialogManager(mContext);
												am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
													@Override
													public void onClick(DialogInterface dialog, int which) {
														// TODO Auto-generated method stub
														switch (which) {
														case DialogInterface.BUTTON_POSITIVE:
															Intent intent = new Intent(getActivity(), LoginActivity.class);
															intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
															startActivity(intent);
															break;
														case DialogInterface.BUTTON_NEGATIVE:
															dialog.dismiss();
															break;
														}
													}
												});
											}
											break;
										case 2:
											db.deleteDownloadLater(item.getSlug());
											remove(item);
											notifyDataSetChanged();
											break;
										}
									}
								});
								popupMenuCompat.show(v);
							}
						}
					});
				}
			}
			return convertView;
		}
	}
	
	private static class ViewHolder {
		ImageView icon;
		TextView name;
		TextView author;
		TextView price;
		ImageView tym;
		ImageButton btnMenu;
	}
	
	private boolean checkLogin(){
		return Utils.getStaticIsLogin(getActivity());
	}
	
	private void validAndBuy(int price, String tymType, DownloadLaterItem item, int versionId){
		if(tymType.equals("green")){
			if(greenTym < price && greenTym != -1){
				AlertDialogManager am = new AlertDialogManager(mContext);
				am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
							List<String> scopes = new ArrayList<String>();
							scopes.add("user.info");
							scopes.add("user.email");
							TopupAPI.getInstance().setContext(getActivity()).topupTYM(scopes, "");
							break;
						case DialogInterface.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						}
					}
				});
			} else if(greenTym == -1){
				AlertDialogManager am = new AlertDialogManager(mContext);
				am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
			} else {
				Intent intent = new Intent(getActivity(), ConfirmBuyActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString(Constants.KEY_IMAGE, item.getImageUrl());
				bundle.putString(Constants.KEY_NAME, item.getAppName());
				bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
				bundle.putInt(Constants.KEY_PRICE_1, item.getPrice1());
				bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
				bundle.putLong(Constants.KEY_VERSION, Long.valueOf(versionId));
				bundle.putString(Constants.KEY_EP, versionName);
				bundle.putString(Constants.KEY_SLUG, item.getSlug());
				intent.putExtras(bundle);
				startActivityForResult(intent, 0);
			}
		} else if(tymType.equals("purple")){
			if(purpleTym < price && purpleTym != -1){
				AlertDialogManager am = new AlertDialogManager(mContext);
				am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
							List<String> scopes = new ArrayList<String>();
							scopes.add("user.info");
							scopes.add("user.email");
							TopupAPI.getInstance().setContext(getActivity()).topupTYM(scopes, "");
							break;
						case DialogInterface.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						}
					}
				});
			} else if(purpleTym == -1){
				AlertDialogManager am = new AlertDialogManager(mContext);
				am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
			} else {
				Intent intent = new Intent(getActivity(), ConfirmBuyActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString(Constants.KEY_IMAGE, item.getImageUrl());
				bundle.putString(Constants.KEY_NAME, item.getAppName());
				bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
				bundle.putInt(Constants.KEY_PRICE_1, item.getPrice1());
				bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
				bundle.putLong(Constants.KEY_VERSION, Long.valueOf(versionId));
				bundle.putString(Constants.KEY_EP, versionName);
				bundle.putString(Constants.KEY_SLUG, item.getSlug());
				intent.putExtras(bundle);
				startActivityForResult(intent, 0);
			}
		} else if(tymType.equals("free")){
			bgTask.getDownloadLink("wish", AccessTokenUtil.getInstance().init(getActivity()).getSavedAccessToken(), item.getSlug(), versionId, Utils.getStaticIsRooted(getActivity()), "direct");
//			bgTask.buyContent("",Utils.getStaticAccessToken(getActivity()), item.getSlug(), versionId);
//			bgTask.buyContent("wish", Utils.getStaticAccessToken(getActivity()), item.getSlug(), versionId);
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		if(requestCode == 0 && resultCode == Activity.RESULT_OK){
			AppMsg.makeText(getActivity(), R.string.buy_success, AppMsg.STYLE_INFO, null).show();
			String accessToken = Utils.getStaticAccessToken(getActivity());
			bgTask.getDownloadLink("wish", accessToken, intent.getExtras().getString(Constants.SLUG), Long.valueOf(intent.getStringExtra(Constants.KEY_VERSION)), Utils.getStaticIsRooted(getActivity()), "direct");
		}
	}
	
	public void onEventMainThread(BuySuccessEvent event){
		if(event.getTopType().equalsIgnoreCase("wish")){
			String accessToken = Utils.getStaticAccessToken(getActivity());
			bgTask.getDownloadLink("wish", accessToken, event.getSlug(), event.getVersionId(), Utils.getStaticIsRooted(getActivity()), "direct");
		}
	}
	
	public void onEventMainThread(BuyFailEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		AppMsg.makeText(getActivity(), event.getMessage(), AppMsg.STYLE_ALERT, null).show();
	}
	public void onEventMainThread(GetDownloadLinkFailEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		AppMsg.makeText(getActivity(), event.getMessage(), AppMsg.STYLE_ALERT, null).show();
	}
	public void onEventMainThread(GetDownloadLinkSuccess event){
		if(event.getTopType().equalsIgnoreCase("wish")){
			if(pDialog != null){
				pDialog.dismiss();
			}
			if(isWatchMovie){
				Intent watch = new Intent(getActivity(), VideoActivity.class);
				watch.putExtra(Constants.MOVIE_URL, event.getDl().getDownload());
				watch.putExtra(Constants.MOVIE_TITLE, contentItem.getAppName());
				watch.putExtra(Constants.MOVIE_EPISODE, versionName);
				startActivity(watch);
			} else {
				DownloadLink download = event.getDl();
				List<String> extraUrls = download.getExtraDownloads();
				String url = download.getDownload();
				Uri _srcUri = Uri.parse(url.replace(" ", "%20"));
				DownloadManager.Request _request = new Request(_srcUri);
				_request.setTitle(contentItem.getAppName());
				_request.setDescription(contentItem.getImageUrl());
				setDownloadData(_request, url);
				downloadManager.enqueue(_request);
				if(extraUrls.size() > 0&& extraUrls.get(0).length()>0){
					for(String extraUrl : extraUrls){
						Uri srcUri = Uri.parse(extraUrl.replace(" ", "%20"));
						DownloadManager.Request request = new Request(srcUri);
						if(extraUrl.endsWith("obb")){
							String obbDir = StorageUtils.OBB_ROOT + contentItem.getPackageName() + "/";
							File obb = new File(obbDir);
							if(!obb.exists()){
								obb.mkdirs();
							}
							request.setDestinationUri(Uri.fromFile(new File(obbDir + Utils.getFileName(extraUrl))));	
						} else {
							request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(extraUrl))));
						}
						request.setTitle(String.format(getResources().getString(R.string.additional_file), contentItem.getAppName()));
						request.setDescription(contentItem.getImageUrl());
						request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
						downloadManager.enqueue(request);
					}
				}
				
			}
		}
	}
	
	private void setDownloadData(Request request, String url){
		if(type.equalsIgnoreCase("android")){
			request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
		} else if(type.equalsIgnoreCase("ebook")){
			request.setMimeType(StorageUtils.EBOOK_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.EBOOK_ROOT + Utils.getFileName(url))));
		} else if(type.equalsIgnoreCase("comic")){
			request.setMimeType(StorageUtils.COMIC_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.COMIC_ROOT + Utils.getFileName(url))));
		} else if(type.equalsIgnoreCase("film")){
			request.setMimeType(StorageUtils.MOVIES_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.MOVIES_ROOT + Utils.getFileName(url))));
		} else {
			request.setMimeType(StorageUtils.DATA_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.DATA_ROOT + Utils.getFileName(url))));
		}
	}
	
	public void onEventMainThread(GetVersionListSuccessEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		if(event.getVersionList().size() == 1){
			if(event.getVersionList().get(0).getPrice1() != 0){
				validAndBuy(event.getVersionList().get(0).getPrice1(), "green", contentItem, event.getVersionList().get(0).getId());
			} else if(event.getVersionList().get(0).getPrice2() != 0){
				validAndBuy(event.getVersionList().get(0).getPrice2(), "purple", contentItem, event.getVersionList().get(0).getId());
			} else {
				pDialog = ProgressDialogManager.showProgressDialog(getActivity(), R.string.loading);
				validAndBuy(0, "free", contentItem, event.getVersionList().get(0).getId());
			}
		} else {
			main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu popupMenu = new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu(mContext);
			popupMenu.setHeaderTitle(getResources().getString(R.string.choose_episode));
			String versionName;
			int versionId;
			int price1;
			int price2;
			for (int i = event.getVersionList().size()-1; i >= 0; i--) {
				versionId = event.getVersionList().get(i).getId();
				versionName = event.getVersionList().get(i).getName();
				price1 = event.getVersionList().get(i).getPrice1();
				price2 = event.getVersionList().get(i).getPrice2();
				popupMenu.add(versionId, versionName, "", price1, price2, true).setIcon(getResources().getDrawable(R.drawable.ic_arrow_down));
			}  
			popupMenu.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(final main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem item) {
					// TODO Auto-generated method stub
					isWatchMovie = true;
					//HomeListFragment.this.versionId = item.getItemId();
					WishlistFragment.this.versionName = item.getTitle();
					if(item.getPrice1() != 0){
						validAndBuy(item.getPrice1(), "green", contentItem, item.getItemId());
					} else if(item.getPrice2() != 0){
						validAndBuy(item.getPrice2(), "purple", contentItem, item.getItemId());
					} else {
						pDialog = ProgressDialogManager.showProgressDialog(mContext, R.string.loading);
						validAndBuy(0, "free", contentItem, item.getItemId());
					}
				}
			});
			popupMenu.show();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int pos, long arg3) {
		// TODO Auto-generated method stub
		DownloadLaterItem item = (DownloadLaterItem) parent.getItemAtPosition(pos);
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.VIEW_EVENT_ACTION, item.getAppName(), Long.valueOf(1));
		Intent intent = new Intent(getActivity(), ItemBrokerActivity.class);
		intent.putExtra(Constants.PREVIOUS_SCREEN, type + "/wishlist");
		intent.putExtra(Constants.SLUG, item.getSlug());
		intent.putExtra(Constants.PACKAGE_NAME, item.getPackageName());
		intent.putExtra(Constants.KEY_REFERER, "direct");
		if(type.equalsIgnoreCase("android")){
			intent.putExtra(Constants.STORE_KEY, "apps");
		} else if(type.equalsIgnoreCase("ebook")){
			intent.putExtra(Constants.STORE_KEY, "books");
		} else if(type.equalsIgnoreCase("comic")){
			intent.putExtra(Constants.STORE_KEY, "comics");
		} else if(type.equalsIgnoreCase("film")){
			intent.putExtra(Constants.STORE_KEY, "movies");
		}
		startActivity(intent);
	}
	
	private class PackageEventReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_ADDED)) {
				String installedName = intent.getDataString().split(":")[1];
				String packageName = "";
				for(DownloadLaterItem item : listItem){
					packageName = item.getPackageName();
					if(packageName == null || !packageName.contains(".")){
						continue;
					}
					if(packageName.equalsIgnoreCase(installedName)){
						item.setInstalled(true);
					}
				}
				adapter.notifyDataSetChanged();
			} else if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_REMOVED)) {
				String packageName = "";
				String uninstalledName = intent.getDataString().split(":")[1];
				for(DownloadLaterItem item : listItem){
					packageName = item.getPackageName();
					if(packageName == null || !packageName.contains(".")){
						continue;
					}
					if(packageName.equalsIgnoreCase(uninstalledName)){
						item.setInstalled(false);
					}
				}
				adapter.notifyDataSetChanged();
			}
		}
	}
}
